package edu.udel.libra.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import edu.udel.libra.model.League;
import edu.udel.libra.model.Player;
import edu.udel.libra.model.FantasyTeam;
import edu.udel.libra.model.User;
import edu.udel.libra.model.repository.LeagueRepository;
import java.util.List;
import java.util.logging.Logger;

@Controller
@SessionAttributes("league")
public class LibraController extends AbstractController
{
	private static final Logger LOG = Logger.getLogger(LibraController.class.getName());

	private static final String INDEX = "index";
	private static final String LOGIN = "login";
	private static final String CREATE_LEAGUE = "create_league";
	
	@Autowired
	private LeagueRepository leagueRepository;
	
	/* Login */
	@RequestMapping("/login")
	public String login(@RequestParam(value="error", required=false) String error, Model model) {
		LOG.info("starting login");
		
		if (isAuthenticated()) return "redirect:/";
    
		if (error != null && error.equals("true")) 
			model.addAttribute("loginFailed", true);
		
		return LOGIN;
	}
	
	/* Main view */
	@RequestMapping("/")
	public String main(Model model) {
		LOG.info("starting main");
    
		if (isAuthenticated()) model.addAttribute("user", getUser());

		return INDEX;
	}
	
	/* Create League GET */
	@RequestMapping(value = "/create_league", method = RequestMethod.GET)
	public String create_league(Model model) {
		LOG.info("starting create_league GET");
		
		User user = getUser();
		
		model.addAttribute("user", user);
		model.addAttribute("league", new League());
		return CREATE_LEAGUE;
	}
	
	/* Create League POST */
	@RequestMapping(value = "/create_league", method = RequestMethod.POST)
	public String create_league(@ModelAttribute("league") League league, Model model, BindingResult result) {
		LOG.info("starting create_league POST");
		
		final User user = getUser();
		
		// TODO: Validation
		
		// If OK
		leagueRepository.save(league);
		// Else
		// model.addAttribute("league", league);
		// return CREATE_LEAGUE;
	
		return "redirect:/fantasy-league/" + league.getId();
	}
	
}
